package com.heba.greenmulu.wxapi;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;

import com.heba.ATApp;
import com.heba.AppManager;
import com.heba.Cfg;
import com.heba.Debug;
import com.heba.config.CommonConfig;
import com.heba.dialog.ErrorDialog;
import com.heba.dialog.MyProgressDialog;
import com.heba.greenmulu.MainActivity;
import com.heba.greenmulu.R;
import com.heba.greenmulu.login.SignUpNewActivity;
import com.heba.greenmulu.user.UserEditActivity;
import com.heba.helper.HttpClientHelper;
import com.heba.helper.JSONHttpHelper;
import com.heba.helper.MemberShipHelper;
import com.heba.utils.ToastShow;
import com.loopj.android.http.RequestParams;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;

import org.json.JSONObject;


/**
 * 微信登陆入口
 * WXEntryActivity
 */
public class WXEntryActivity extends AppCompatActivity implements IWXAPIEventHandler {

    private MyProgressDialog progressDialog;

    private String code;    //授权临时票据
    private String state;   //判断是微信登录还是绑定微信

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        progressDialog = new MyProgressDialog(this, getResources().getString(R.string.loading));
        handleIntent(getIntent());
    }

    protected void handleIntent(Intent paramIntent) {
        ATApp.api.handleIntent(paramIntent, this);
    }

    @Override
    public void onReq(BaseReq baseReq) {
    }

    @Override
    public void onResp(BaseResp baseResp) {
        Debug.Log("WX BaseResp", "baseResp.errCode=" + baseResp.errCode);
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                //微信登录回调
                Debug.Log("wechate onResp ", "微信登录信息");
                try {
                    SendAuth.Resp req = (SendAuth.Resp) baseResp;
                    if (req == null) {
                        Debug.Log("req is null", "");
                    } else {
                        Debug.Log("code is", req.code + " type is " + req.getType() + " state is " + req.state);
                        code = req.code; //授权临时票据
                        state = req.state;  //用于判断是登录还是绑定
                        Debug.Log("code is ", code);
                        Debug.Log("state is ", state);
                        getWxToken();
                    }
                } catch (Exception e) {
                    Debug.Log("处理ShareSDK微信分享", "");
                    finish();
                    e.printStackTrace();
                }
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                WXEntryActivity.this.finish();
                break;
            default:
                break;
        }
    }

    /**
     * 通过code获取access_token
     */
    private void getWxToken() {
        progressDialog.show();

        Debug.Log("getWxToken ", "");
        HttpClientHelper client = new HttpClientHelper();
        RequestParams params = new RequestParams();
        params.put("appid", ATApp.AppID);
        params.put("secret", ATApp.AppSecret);
        params.put("code", code);
        params.put("grant_type", "authorization_code");
        client.post("https://api.weixin.qq.com/sns/oauth2/access_token?", params, new JSONHttpHelper.JSONHttpResponseHandler(this) {
            @Override
            public void Success() {
                super.Success();
                Debug.Log("getWxToken ", "Success");
                try {
                    if (!response.isEmpty()) {
                        JSONObject jsonObject = new JSONObject(response);
                        String access_token = jsonObject.getString("access_token");
                        String expires_in = jsonObject.getString("expires_in");
                        String refresh_token = jsonObject.getString("refresh_token");
                        String openid = jsonObject.getString("openid");
                        String scope = jsonObject.getString("scope");

                        if (state.equals("greenmulu_wx_bind")) {
                            //绑定微信
                            bindWechat(access_token, openid);
                        } else {
                            //获取用户信息
                            getUserInfo(access_token, openid);
                        }

                    }
                } catch (Exception e) {
                    progressDialog.dismiss();
                    e.printStackTrace();
                }
            }

            @Override
            public void Failure() {
                Debug.Log("getWxToken ", "Failure");
                progressDialog.dismiss();
                super.Failure();
            }
        });
    }

    /**
     * 获取用户基本信息
     *
     * @param token
     * @param openid
     */
    private void getUserInfo(String token, String openid) {
        Debug.Log("getUserInfo ", "");
        HttpClientHelper client = new HttpClientHelper();
        RequestParams params = new RequestParams();
        params.put("access_token", token);
        params.put("openid", openid);
        client.post("https://api.weixin.qq.com/sns/userinfo?", params, new JSONHttpHelper.JSONHttpResponseHandler(this) {
            @Override
            public void Success() {
                super.Success();
                Debug.Log("getUserInfo ", "Success");
                try {
                    if (!response.isEmpty()) {
                        JSONObject jsonObject = new JSONObject(response);
                        final String openid = jsonObject.getString("openid"); //普通用户的标识，对当前开发者帐号唯一
//                        String nickname = URLEncoder.encode(jsonObject.getString("nickname"), "UTF-8");
                        String nickname = jsonObject.getString("nickname");
                        String sex = jsonObject.getString("sex");
                        String headimgurl = jsonObject.getString("headimgurl");
                        String unionid = jsonObject.getString("unionid");  //用户统一标识。针对一个微信开放平台帐号下的应用，同一用户的unionid是唯一的。

                        //发送用户信息至服务器
                        progressDialog.show();
                        new MemberShipHelper(new MemberShipHelper.MembershipListener() {
                            @Override
                            public void Success() {
                                //如果用户没有完善信息，则跳转到完善信息界面
                                if (Cfg.Account.isEmpty() || Cfg.Email.isEmpty()) {
                                    Bundle bundle = new Bundle();
                                    bundle.putString(CommonConfig.SIGNUP_TITLE, context.getResources().getString(R.string.sign_up_with_wechat));
                                    bundle.putString(CommonConfig.SIGNUP_ICON, Cfg.Icon);
                                    bundle.putString(CommonConfig.SIGNUP_FIRSTNAME, Cfg.NickName);
                                    bundle.putInt(CommonConfig.TYPE, SignUpNewActivity.TYPE_SOCIAL_LOGIN);
                                    openActivity(SignUpNewActivity.class, bundle);
                                    finish();
                                } else {
                                    //用户已完善信息则跳转到首页
                                    AppManager.getAppManager().finishAllActivity();
                                    openActivity(MainActivity.class, null);
                                    ToastShow.displayToast(WXEntryActivity.this, getResources().getString(R.string.login_success));
                                }
                                progressDialog.dismiss();
                            }

                            @Override
                            public void Fail(String error) {
                                finish();
                                progressDialog.dismiss();
                                ToastShow.displayToast(WXEntryActivity.this, getResources().getString(R.string.login_failure));
                            }
                        }).wechatLogin(WXEntryActivity.this, openid, unionid, nickname, headimgurl);
                    }
                } catch (Exception e) {
                    finish();
                    progressDialog.dismiss();
                    e.printStackTrace();
                }
            }

            @Override
            public void Failure() {
                Debug.Log("getUserInfo ", "Failure");
                finish();
                progressDialog.dismiss();
                super.Failure();
            }
        });
    }

    /**
     * 绑定微信
     *
     * @param token
     * @param openid
     */
    private void bindWechat(String token, String openid) {
        HttpClientHelper client = new HttpClientHelper();
        RequestParams params = new RequestParams();
        params.put("access_token", token);
        params.put("openid", openid);
        client.post("https://api.weixin.qq.com/sns/userinfo?", params, new JSONHttpHelper.JSONHttpResponseHandler(this) {
            @Override
            public void Success() {
                super.Success();
                try {
                    if (!response.isEmpty()) {
                        JSONObject jsonObject = new JSONObject(response);
                        final String openid = jsonObject.getString("openid"); //普通用户的标识，对当前开发者帐号唯一
//                        String nickname = URLEncoder.encode(jsonObject.getString("nickname"), "UTF-8");
                        String nickname = jsonObject.getString("nickname");
                        String sex = jsonObject.getString("sex");
                        String headimgurl = jsonObject.getString("headimgurl");
                        String unionid = jsonObject.getString("unionid");  //用户统一标识。针对一个微信开放平台帐号下的应用，同一用户的unionid是唯一的。

                        //发送用户信息至服务器
                        progressDialog.show();
                        new MemberShipHelper(new MemberShipHelper.MembershipListener() {
                            @Override
                            public void Success() {
                                AppManager.getAppManager().finishActivity(UserEditActivity.class);
                                finish();
                                progressDialog.dismiss();
                                ToastShow.displayToast(WXEntryActivity.this, getResources().getString(R.string.bind_success));
                            }

                            @Override
                            public void Fail(String error) {
                                progressDialog.dismiss();
                                ErrorDialog.showWithConfirmClick(context, context.getResources().getString(R.string.tips), error, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        finish();
                                        ToastShow.displayToast(WXEntryActivity.this, getResources().getString(R.string.bind_failure));
                                    }
                                });
                            }
                        }).bindWechat(WXEntryActivity.this, openid, unionid);
                    }
                } catch (Exception e) {
                    finish();
                    progressDialog.dismiss();
                    e.printStackTrace();
                }
            }

            @Override
            public void Failure() {
                finish();
                super.Failure();
            }
        });
    }

    /**
     * openActivity
     *
     * @param pClass
     * @param pBundle
     */
    private void openActivity(Class<?> pClass, Bundle pBundle) {
        Intent intent = new Intent(this, pClass);
        if (pBundle != null) {
            intent.putExtras(pBundle);
        }
        startActivity(intent);
        overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}